// pages/buy/buy.js
import {
  getCardType,
  getMyCardGoods,
  getVipGoodsCatNum
} from '../../apis/api'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    ShopName: [],
    index: 0,
    getList: [],
    vegetableList: [],
    meetList: [],
    eggList: [],
    riceList: [],
    fishList: [],
    bestList: [],
    cornList: [],
    fruitList: [],
    birdList: [],
    meetliveList: [],
    freeList: [],
    vegetableLimit: 0,
    meetLimit: 0,
    eggLimit: 0,
    riceLimit: 0,
    fishLimit: 0,
    bestLimit: 0,
    cornLimit: 0,
    fruitLimit: 0,
    birdLimit: 0,
    meetliveLimit: 0,
    freeLimit: 0,
    allList: [],
    allCatList: [],
    card_id: 0,
    submitId: 0,
    cardList: [],
    submitCardAccount: '',
    thisShow: false,
    token: '',
    card_type: '',
    upperLimit: []
  },
  // 子传父数据
  myevent(e) {
    
    if (e.detail.goodC === '蔬菜类') {
      this.setData({
        vegetableList: e.detail.good
      })
      wx.setStorageSync('vegetableList', e.detail.good)
    }
    if (e.detail.goodC === '肉类') {
      this.setData({
        meetList: e.detail.good
      })
      wx.setStorageSync('meetList', e.detail.good)
    }
    if (e.detail.goodC === '蛋类') {
      this.setData({
        eggList: e.detail.good
      })
      wx.setStorageSync('eggList', e.detail.good)
    }
    if (e.detail.goodC === '大米类') {
      this.setData({
        riceList: e.detail.good
      })
      wx.setStorageSync('riceList', e.detail.good)
    }
    if (e.detail.goodC === '水产类') {
      this.setData({
        fishList: e.detail.good
      })
      wx.setStorageSync('fishList', e.detail.good)
    }
    if (e.detail.goodC === '特产类') {
      this.setData({
        bestList: e.detail.good
      })
      wx.setStorageSync('bestList', e.detail.good)
    }
    if (e.detail.goodC === '玉米类') {
      this.setData({
        cornList: e.detail.good
      })
      wx.setStorageSync('cornList', e.detail.good)
    }
    if (e.detail.goodC === '水果类') {
      this.setData({
        fruitList: e.detail.good
      })
      wx.setStorageSync('fruitList', e.detail.good)
    }
    if (e.detail.goodC === '禽类') {
      this.setData({
        birdList: e.detail.good
      })
      wx.setStorageSync('birdList', e.detail.good)
    }
    if (e.detail.goodC === '畜肉类') {
      this.setData({
        meetliveList: e.detail.good
      })
      wx.setStorageSync('meetliveList', e.detail.good)
    }
    if (e.detail.goodC === '赠品类') {
      this.setData({
        freeList: e.detail.good
      })
      wx.setStorageSync('freeList', e.detail.good)
    }
    // this.changeListToOne()
  },
  // 卡类型id判断
  selectVipType: async function (that) {
    if (!!that) {
      // this.setData({
      //   vegetableList: [],
      //   meetList: [],
      //   eggList: [],
      //   fishList: [],
      //   bestList: [],
      //   riceList: [],
      //   cornList: [],
      //   fruitList: [],
      //   birdList: [],
      //   meetliveList: []
      // })
      let that_id = that
      this.setData({
        card_id: that_id
      })
      // 获取菜品分类上限
      console.log({
        cardType: this.data.card_type
      });
      const req = await getVipGoodsCatNum({
        cardType: this.data.card_type
      })
      console.log(req);
      const upperLimitMiddle = []
      if (!!req) {
        for (let i = 0; i < req.data.length; i++) {
          upperLimitMiddle.push(req.data[i].upperLimit)
          // console.log(req.data[i])
        }
        this.setData({
          upperLimit: upperLimitMiddle
        })
        this.setData({
          vegetableLimit: upperLimitMiddle[0],
          meetLimit: upperLimitMiddle[1],
          eggLimit: upperLimitMiddle[2],
          riceLimit: upperLimitMiddle[8],
          fishLimit: upperLimitMiddle[7],
          bestLimit: upperLimitMiddle[9],
          cornLimit: upperLimitMiddle[4],
          fruitLimit: upperLimitMiddle[5],
          birdLimit: upperLimitMiddle[3],
          meetliveLimit: upperLimitMiddle[6],
          freeLimit: upperLimitMiddle[10],
        })
      }
      const res = await getMyCardGoods({
        cardId: that_id
      })
      console.log(res);
      if (!!res.data) {
        this.setData({
          thisShow: true
        })
      } else {
        this.setData({
          thisShow: false
        })
      }
      const mList = []
      const vList = []
      const eList = []
      const fList = []
      const bList = []
      const rList = []
      const cList = []
      const ffList = []
      const bbList = []
      const mmList = []
      const fffList = []
      for (let i = 0; i < res.data.length; i++) {
      
        if (res.data[i].availableQuantity !== 0 && res.data[i].totalInventory !== 0) {
          if (res.data[i].dishType === '肉') {
            if (!res.data[i].buyNum) res.data[i].buyNum = 0
            mList.push(res.data[i])
          }
          if (res.data[i].dishType === '蛋') {
            if (!res.data[i].buyNum) res.data[i].buyNum = 0
            eList.push(res.data[i])
          }
          if (res.data[i].dishType === '蔬菜') {
            if (!res.data[i].buyNum) res.data[i].buyNum = 0
            vList.push(res.data[i])
          }
          if (res.data[i].dishType === '大米') {
            if (!res.data[i].buyNum) res.data[i].buyNum = 0
            rList.push(res.data[i])
          }
          if (res.data[i].dishType === '水产') {
            if (!res.data[i].buyNum) res.data[i].buyNum = 0
            fList.push(res.data[i])
          }
          if (res.data[i].dishType === '特产') {
            if (!res.data[i].buyNum) res.data[i].buyNum = 0
            bList.push(res.data[i])
          }
          if (res.data[i].dishType === '玉米') {
            if (!res.data[i].buyNum) res.data[i].buyNum = 0
            cList.push(res.data[i])
          }
          if (res.data[i].dishType === '水果') {
            if (!res.data[i].buyNum) res.data[i].buyNum = 0
            ffList.push(res.data[i])
          }
          if (res.data[i].dishType === '禽类') {
            if (!res.data[i].buyNum) res.data[i].buyNum = 0
            bbList.push(res.data[i])
          }
          if (res.data[i].dishType === '畜肉') {
            if (!res.data[i].buyNum) res.data[i].buyNum = 0
            mmList.push(res.data[i])
          }
          if (res.data[i].dishType === '赠品') {
            if (!res.data[i].buyNum) res.data[i].buyNum = 0
            fffList.push(res.data[i])
          }
        }
      }
      this.setData({
        vegetableList: vList,
        meetList: mList,
        eggList: eList,
        fishList: fList,
        bestList: bList,
        riceList: rList,
        cornList: cList,
        fruitList: ffList,
        birdList: bbList,
        meetliveList: mmList,
        freeList: fffList,
      })
    }
  },

  toToolOne(list) {
    const toolList = []
    for (let i = 0; i < list.length; i++) {
      if (list[i].buyNum !== 0) toolList.push(list[i])
    }
    return toolList
  },
  // 将选择的菜品集成
  changeListToOne() {
    const vTool = this.toToolOne(wx.getStorageSync('vegetableList'))
    const mTool = this.toToolOne(wx.getStorageSync('meetList'))
    const eTool = this.toToolOne(wx.getStorageSync('eggList'))
    const rTool = this.toToolOne(wx.getStorageSync('riceList'))
    const fTool = this.toToolOne(wx.getStorageSync('fishList'))
    const bTool = this.toToolOne(wx.getStorageSync('bestList'))
    const cTool = this.toToolOne(wx.getStorageSync('cornList'))
    const ffTool = this.toToolOne(wx.getStorageSync('fruitList'))
    const bbTool = this.toToolOne(wx.getStorageSync('birdList'))
    const mmTool = this.toToolOne(wx.getStorageSync('meetliveList'))
    const fffTool = this.toToolOne(wx.getStorageSync('freeList'))
    this.setData({
      allList: [...vTool, ...mTool, ...eTool, ...rTool, ...fTool, ...bTool, ...cTool, ...ffTool, ...bbTool, ...mmTool, ...fffTool]
    })
  },
  nextBuy(e) {
    this.changeListToOne()
    console.log(this.data.allList);
    if (this.data.allList.length === 0) return wx.showToast({
      title: '暂未选择菜品',
      icon: 'error'
    })
    else {
      let middle = []
      for (let i = 0; i < this.data.allList.length; i++) {
        middle.push(this.data.allList[i].dishType)
      }
      middle = Array.from(new Set(middle))
      let vArray1 = this.data.allCatList.reduce((a, c) => {
        a[c] = c
        return a
      }, {})
      let vArray2 = middle.reduce((a, c) => {
        a[c] = c
        return a
      }, {})
      const result = this.data.allCatList.filter(c => {
        console.log('vArray2[c]', vArray2[c]);
        return !vArray2[c]
      }).concat(middle.filter(c => {
        console.log('vArray1[c]', vArray1[c]);
        return !vArray1[c]
      }))
      let question = result.join('、')
      const _this = this

      let vTool = 0
      let mTool = 0
      let eTool = 0
      let rTool = 0
      let fTool = 0
      let bTool = 0
      let cTool = 0
      let ffTool = 0
      let bbTool = 0
      let mmTool = 0
      let fffTool = 0
      for (let i = 0; i < this.data.allList.length; i++) {
        if (this.data.allList[i].dishType === '蔬菜') {
          vTool += this.data.allList[i].buyNum
        }
        if (this.data.allList[i].dishType === '肉') {
          mTool += this.data.allList[i].buyNum
        }
        if (this.data.allList[i].dishType === '蛋') {
          eTool += this.data.allList[i].buyNum
        }
        if (this.data.allList[i].dishType === '大米') {
          rTool += this.data.allList[i].buyNum
        }
        if (this.data.allList[i].dishType === '水产') {
          fTool += this.data.allList[i].buyNum
        }
        if (this.data.allList[i].dishType === '特产') {
          bTool += this.data.allList[i].buyNum
        }
        if (this.data.allList[i].dishType === '玉米') {
          cTool += this.data.allList[i].buyNum
        }
        if (this.data.allList[i].dishType === '水果') {
          ffTool += this.data.allList[i].buyNum
        }
        if (this.data.allList[i].dishType === '禽类') {
          bbTool += this.data.allList[i].buyNum
        }
        if (this.data.allList[i].dishType === '畜肉') {
          mmTool += this.data.allList[i].buyNum
        }
        if (this.data.allList[i].dishType === '赠品') {
          fffTool += this.data.allList[i].buyNum
        }
      }
      let isGO = false
      const isGOObject = []
      for(let i = 0; i < this.data.allCatList.length; i++) {
        if(this.data.allCatList[i] === '蔬菜') {
          isGOObject.push({type: '蔬菜', num: vTool, limit: this.data.vegetableLimit})
        }
        if(this.data.allCatList[i] === '肉') {
          isGOObject.push({type: '肉', num: mTool, limit: this.data.meetLimit})
        }
        if(this.data.allCatList[i] === '蛋') {
          isGOObject.push({type: '蛋', num: eTool, limit: this.data.eggLimit})
        }
        if(this.data.allCatList[i] === '大米') {
          isGOObject.push({type: '大米', num: rTool, limit: this.data.riceLimit})
        }
        if(this.data.allCatList[i] === '水产') {
          isGOObject.push({type: '水产', num: fTool, limit: this.data.fishLimit})
        }
        if(this.data.allCatList[i] === '特产') {
          isGOObject.push({type: '特产', num: bTool, limit: this.data.bestLimit})
        }
        if(this.data.allCatList[i] === '玉米') {
          isGOObject.push({type: '玉米', num: cTool, limit: this.data.cornLimit})
        }
        if(this.data.allCatList[i] === '水果') {
          isGOObject.push({type: '水果', num: ffTool, limit: this.data.fruitLimit})
        }
        if(this.data.allCatList[i] === '禽类') {
          isGOObject.push({type: '禽类', num: bbTool, limit: this.data.birdLimit})
        }
        if(this.data.allCatList[i] === '畜肉') {
          isGOObject.push({type: '畜肉', num: mmTool, limit: this.data.meetliveLimit})
        }
        if(this.data.allCatList[i] === '赠品') {
          isGOObject.push({type: '赠品', num: fffTool, limit: this.data.freeLimit})
        }
      }
      const baga = []
      for(let i = 0; i < isGOObject.length; i++) {
        if(isGOObject[i].limit !== '*' && isGOObject[i].limit-0 !== isGOObject[i].num) {
          baga.push(isGOObject[i].type + '可选' + isGOObject[i].limit + '份未选满')
        }
        if(isGOObject[i].limit === '*' && isGOObject[i].num === 0) {
          baga.push(isGOObject[i].type + '可任选却未选择')
        }
      }
      let questionGo = baga.join('、')
      if (baga.length !== 0) {
        return wx.showModal({
          title: '提 示',
          content: questionGo + '，是否确认选择完毕，继续下单',
          cancelText: '返回选择',
          success(res) {
            if (res.confirm) {
              const list = JSON.stringify(_this.data.allList)
              const card_ids = _this.data.submitId
              const card_types = _this.data.submitCardAccount
              const type=_this.data.card_type
              wx.navigateTo({
                url: `/pages/tobuy/tobuy?list=${list}&card=${card_ids}&cardtype=${card_types}&type=${type}`
              })
            }
          }
        })
      }
      const list = JSON.stringify(_this.data.allList)
      const card_ids = _this.data.submitId
      const card_types = _this.data.submitCardAccount
      const type=_this.data.card_type
      wx.navigateTo({
        url: `/pages/tobuy/tobuy?list=${list}&card=${card_ids}&cardtype=${card_types}&type=${type}`
      })
    }
  },
  // 判断拥有的菜分类
  getAllGoodCat() {
    const middle = [{
        cat: '蔬菜',
        num: this.data.vegetableList.length
      },
      {
        cat: '肉',
        num: this.data.meetList.length
      },
      {
        cat: '蛋',
        num: this.data.eggList.length
      },
      {
        cat: '水产',
        num: this.data.fishList.length
      },
      {
        cat: '特产',
        num: this.data.bestList.length
      },
      {
        cat: '大米',
        num: this.data.riceList.length
      },
      {
        cat: '玉米',
        num: this.data.cornList.length
      },
      {
        cat: '水果',
        num: this.data.fruitList.length
      },
      {
        cat: '禽类',
        num: this.data.birdList.length
      },
      {
        cat: '畜肉',
        num: this.data.meetliveList.length
      },
      {
        cat: '赠品',
        num: this.data.freeList.length
      }
    ]
    const toGC = []
    for (let i = 0; i < middle.length; i++) {
      if (middle[i].num !== 0) toGC.push(middle[i].cat)
    }
    this.setData({
      allCatList: toGC
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    if (!!wx.getStorageSync('token')) {
      this.setData({
        token: wx.getStorageSync('token'),
        card_id: options.id,
        submitId: options.id,
        submitCardAccount: options.card,
        card_type: options.type,
        vegetableList: wx.getStorageSync('vegetableList'),
        meetList: wx.getStorageSync('meetList'),
        eggList: wx.getStorageSync('eggList'),
        riceList: wx.getStorageSync('riceList'),
        fishList: wx.getStorageSync('fishList'),
        bestList: wx.getStorageSync('bestList'),
        cornList: wx.getStorageSync('cornList'),
        fruitList: wx.getStorageSync('fruitList'),
        birdList: wx.getStorageSync('birdList'),
        meetliveList: wx.getStorageSync('meetliveList'),
        freeList: wx.getStorageSync('freeList')
      })
    }
    if (!!this.data.token) {
      await this.selectVipType(this.data.card_id)
      this.getAllGoodCat()
    } else {
      wx.showModal({
        title: '提示',
        content: '下单功能需要登录，是否前往登录',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/tolog/tolog',
            })
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    if (!!wx.getStorageSync('token')) {
      this.setData({
        vegetableList: wx.getStorageSync('vegetableList'),
        meetList: wx.getStorageSync('meetList'),
        eggList: wx.getStorageSync('eggList'),
        riceList: wx.getStorageSync('riceList'),
        fishList: wx.getStorageSync('fishList'),
        bestList: wx.getStorageSync('bestList'),
        cornList: wx.getStorageSync('cornList'),
        fruitList: wx.getStorageSync('fruitList'),
        birdList: wx.getStorageSync('birdList'),
        meetliveList: wx.getStorageSync('meetliveList'),
        freeList: wx.getStorageSync('freeList')
      })
    }
    if (!!this.data.token) {
      await this.selectVipType(this.data.card_id)
      this.getAllGoodCat()
    } else {
      wx.showModal({
        title: '提示',
        content: '下单功能需要登录，是否前往登录',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/tolog/tolog',
            })
          }
        }
      })
    }
  }
})